import { useCallback } from 'react';
import { connect } from 'umi';
import { Menu, Item, useContextMenu } from 'react-contexify';
import 'react-contexify/dist/ReactContexify.css';

/**
 * 小部件右键菜单
 * @param {*} props 
 * @returns 
 */
const ContextMenu = props => {
  const { children, className, dispatch, currNode } = props;
  const MENU_ID = 'contextMenuId';

  const handleDelete = () => {
    if (currNode) {
      dispatch({
        type: 'editor/delNodeData',
        payload: currNode,
      });
    }
  };

  const handleCopy = () => {
    if (currNode) {
      //TODO: 
    }
  };

  const handleItemClick = type => {
    if (type === 'del') {
      handleDelete();
    } else if (type === 'copy') {
      handleCopy();
    }
  };

  const { show } = useContextMenu({
    id: MENU_ID,
  });

  function handleContextMenu(e) {
    e.preventDefault();
    show(event);
  }

  return (
    <>
      <div className={className} onContextMenu={handleContextMenu}>
        {children}
      </div>
      <Menu id={MENU_ID}>
        <Item onClick={() => handleItemClick('copy')}>复制</Item>
        <Item onClick={() => handleItemClick('del')}>删除</Item>
      </Menu>
    </>
  );
};

export default connect(({ editor }) => ({
  currNode: editor.currNode,
}))(ContextMenu);